﻿using System.Linq;
using JustAgile.Html.Linq;
using NovelDB.Entity;

namespace NovelLibEx.Parser
{
    /// <summary>
    /// http://www.pashu.org    爬书网
    /// </summary>
    public class PashuParser : NovelLibEx.Parser.INovelParser
    {
        /// <summary>
        /// 使用Linq to html进行解析
        /// 发现用这个库解析实在是太过于方便了
        /// </summary>
        /// <param name="strContent"></param>
        /// <returns></returns>
        public Novel ExtractNovelCatelogLinks(string baseUrl, string strContent)
        {
            HDocument doc = HDocument.Parse(strContent);
            // 首先，找出是小说链接的内容。这样可以过滤掉广告信息
            var BookText = (from chapter in doc.Descendants("div")
                            where chapter.Attribute("id") != null && chapter.Attribute("id").Value == "BookText"
                            select chapter
                            ).First();

            // 小说分段是通过<ul>进行的，所以查找出几个ul就代表有几个章节
            var chapters = (from chapter in BookText.Descendants("ul")
                            select chapter).ToList();

            Novel novel = new Novel();
            int idOfChapter = 0;
            int idOfLink = 0;
            foreach (var chapter in chapters)
            {
                NovelChapter chap = new NovelChapter();

                // 章节名就是<ul>标签的最靠近的div标签的内容
                var chapterName = chapter.ElementsBeforeSelf("div").Last().Value;
                var links = (from link in chapter.Descendants("a")
                             select link).ToList();

                chap.Name = chapterName;
                chap.ChapterId = idOfChapter;

                foreach (var link in links)
                {
                    NovelLink novelLink = new NovelLink
                    {
                        Href = link.Attribute("href").Value,
                        Title = link.Attribute("title").Value,
                        Description = link.Value,
                        LinkId = idOfLink,
                        SiteUrl = baseUrl,
                        IsUpdated = false,
                        UpdateTime = ""
                    };
                    
                    chap.NovelLinks.Add(novelLink);

                    idOfLink++;
                }

                novel.NovelChapters.Add(chap);
                idOfChapter++;
            }

            return novel;
        }

        /// <summary>
        /// 移除小说中的广告文字
        /// </summary>
        /// <param name="strContent"></param>
        /// <returns></returns>
        public string RemoveAd(string strContent)
        {
            HDocument hDoc = HDocument.Parse(strContent);
            HElement ele = (from c in hDoc.Descendants("div")
                            where c.Attribute("id").Value == "Content"
                            select c).FirstOrDefault();

            // 移除垃圾文字。
            var ads = (from e in ele.Descendants("div")
                        where e.HasAttributes 
                        select e).ToList();

            foreach (HElement ad in ads)
            {
                foreach (HAttribute att in ad.Attributes())
                {
                    if ((att.Name == "style") && (ad.Attribute("style").Value == "display:none"))
                    {
                        ad.Remove();
                        break;
                    }

                }
            }

            // 移除LinkMenu
            var menu = (from e in ele.Descendants("div")
                        where e.FirstAttribute.Name == "id"
                        && (e.Attribute("id").Value == "LinkMenu" 
                        || e.Attribute("id").Value == "EndMenu")
                        select e).ToList();
            menu.ForEach(x => x.Remove());

            // 移除所有script
            var scripts = (from e in ele.Descendants("script")
                           select e).ToList();
            scripts.ForEach(x => x.Remove());

            // 移除table。只移除最后一个，前面的还有用
            var tables = (from e in ele.Descendants("table")
                          select e).ToList();
            tables.Last().Remove(); // (x => x.Remove());

            // 移除
            // <a href="/User/Messages.aspx?to=pashu&amp;title=《斗破苍穹》正文,第三十五章 罪恶感" target="_blank"><span style="color:#FF0000;">【更新慢或者章节错误，点击举报（请详细说明）】</span></a><br /></td>
            var lins = (from e in ele.Descendants("a")
                        where e.Attribute("href").Value.Contains("Messages.aspx")
                        select e).ToList();
            lins.ForEach(x => x.Remove());

            strContent = ele.ToString();

            return strContent;
        }
    }
}
